<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float:right" type="primary" @click="handleSearchList()" size="small">查询搜索</el-button>
        <el-button
          style="float:right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small"
        >重置</el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="版本号">
            <el-input v-model="listQuery.keyword" class="input-width" placeholder="版本号"></el-input>
          </el-form-item>
          <el-form-item label="版本类型">
            <el-select v-model="listQuery.appType" placeholder="版本类型" style="width:100%">
              <el-option label="所有类型" value="null"></el-option>
              <el-option label="ios" value="ios"></el-option>
              <el-option label="android" value="android"></el-option>
              <el-option label="其他" value="other"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否强升">
            <el-select v-model="listQuery.status" placeholder="是否强升" style="width:100%">
              <el-option label="全部" value="null"></el-option>
              <el-option label="是" value="0"></el-option>
              <el-option label="否" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>包管理列表</span>
      <el-button size="mini" class="btn-add" @click="createActivity()">创建新包</el-button>
    </el-card>

    <div class="table-container">
      <el-table
        ref="newProductTable"
        :data="integralList"
        @selection-change="handleSelectionChange"
        v-loading="listLoading"
        style="width: 100%;"
        border
      >
        <el-table-column type="selection" width="60" align="center"></el-table-column>

        <el-table-column label="版本类型" align="center">
          <template slot-scope="scope">{{scope.row.appType | clientStatus}}</template>
        </el-table-column>
        <el-table-column label="提交时间" width="180" align="center">
          <template slot-scope="scope">{{scope.row.createTime | formatCreateTime}}</template>
        </el-table-column>
        <el-table-column label="是否强升" align="center">
          <template slot-scope="scope">{{scope.row.mustUpdate|ListStatus}}</template>
        </el-table-column>
        <el-table-column label="版本号" align="center">
          <template slot-scope="scope">{{scope.row.versionNum}}</template>
        </el-table-column>
        <el-table-column label="版本描述" align="center">
          <template slot-scope="scope">{{scope.row.versionDesc}}</template>
        </el-table-column>
        <el-table-column label="下载地址" align="center">
          <template slot-scope="scope">{{scope.row.url}}</template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEditSort(scope.$index, scope.row)"
            >修改</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="batch-operate-container">
      <el-select size="small" v-model="operateType" placeholder="批量操作">
        <el-option
          v-for="item in operates"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <el-button
        style="margin-left: 20px"
        class="search-button"
        @click="handleBatchOperate()"
        type="primary"
        size="small"
      >确定</el-button>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pageSize"
        :page-sizes="[5,10,15]"
        :current-page.sync="listQuery.pageNum"
        :total="total"
      ></el-pagination>
    </div>
    <el-dialog title="操作" :visible.sync="selectDialogVisible" width="50%" :destroy-on-close="true">
      <el-form
        :model="intergralForm"
        :rules="intergralFormRules"
        status-icon
        ref="intergralForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="版本号" prop="versionNum">
          <el-input v-model="intergralForm.versionNum"></el-input>
        </el-form-item>
        <el-form-item label="版本类型" prop="appType">
          <el-select v-model="intergralForm.appType" placeholder="请选择版本类型" style="width:100%">
            <el-option label="ios" value="ios"></el-option>
            <el-option label="android" value="android"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否强升" prop="appType">
          <el-select v-model="intergralForm.mustUpdate" placeholder="请选择是否强升" style="width:100%">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本描述" prop="versionDesc">
          <el-input v-model="intergralForm.versionDesc"></el-input>
        </el-form-item>
        <el-form-item label="下载地址" prop="url">
          <el-input v-model="intergralForm.url" disabled></el-input>
        </el-form-item>
        <el-form-item>
            <el-upload
              class="upload-demo"
              drag
              action="https://store-images-release.oss-cn-hangzhou.aliyuncs.com"
              :on-success="handleSuccess"
              :before-upload="beforeUpload"
              :data="dataObj"
              :limit='1'
              :on-exceed="handleExceed"
              multiple
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {
  fetchList,
  deleteAppPackage,
  updateAppPackageProduct,
  insertPackage,
  fetchQuoteProduct
} from "@/api/appPackage";
import { fetchList as fetchProductList } from "@/api/product";
import { validatInteger } from "@/utils/validate";
import {
  ruleName,
  regMinScore,
  regMaxScore,
  maxTotalScore,
  dayTotalScore,
  dateNum
} from "./utils/rule";
import moment from "moment";
import { formatDate } from "@/utils/date";
import { policy } from "@/api/oss";

const defaultListQuery = {
  pageNum: 1,
  pageSize: 5,
  roleName: "",
  clientId: "",
  status: "null"
};
const defaultRecommendOptions = [
  {
    label: "未推荐",
    value: 0
  },
  {
    label: "推荐中",
    value: 1
  }
];
export default {
  name: "appPackage",
  data() {
    // 数字限定
    let isInteger = (rule, value, callback, text) => {
      if (value === "") {
        callback(new Error(text + "不能为空"));
      } else {
        if (!validatInteger(value)) {
          callback(new Error(text + "只能为大于零的整数"));
        }
        callback();
      }
    };
    // let ruleName = (rule, value, callback,text) => {
    //   if (value === '') {
    //     callback(new Error(text+'不能为空'));
    //   } else {
    //     if (!validatInteger(value)) {
    //       callback(new Error(text+'只能为大于零的整数'));
    //     }
    //     callback();
    //   }
    // };
    return {
      listObj: {},
      fileList: [],
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: ""
      },
      listQuery: Object.assign({}, defaultListQuery),
      recommendOptions: Object.assign({}, defaultRecommendOptions),
      integralList: null,
      total: null,
      listLoading: false,
      multipleSelection: [],
      type: 1,
      activityTime: [],
      operates: [
        {
          label: "删除",
          value: 1
        }
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      operateType: null,
      selectDialogVisible: false,
      dialogData: {
        list: null,
        total: null,
        multipleSelection: [],
        listQuery: {
          keyword: null,
          pageNum: 1,
          pageSize: 5
        }
      },
      isCreate: true,
      sortDialogData: { dayNum: "", limitNum: "", ids: [] },
      // 创建表单数据源
      intergralForm: {
        appType: "",
        mustUpdate: "",
        versionNum: "",
        versionDesc: "",
        url: ""
      },

      sortChSGoodsData: { dayNum: "", limitNum: "" },
      sortRules: {
        dayNum: [
          {
            required: true,
            validator: (rule, value, callback) => {
              isInteger(rule, value, callback, "限购时间");
            },
            trigger: "blur"
          }
        ],
        limitNum: [
          {
            required: true,
            validator: (rule, value, callback) => {
              isInteger(rule, value, callback, "限购数量");
            },
            trigger: "blur"
          }
        ]
      },
      intergralFormRules: {
        appType: [
          { required: true, message: "请选择版本类型", trigger: "blur" }
        ],
        mustUpdate: [
          { required: true, message: "请选择是否强升", trigger: "blur" }
        ],
        versionNum: [
          { required: true, message: "请填写版本号", trigger: "blur" }
        ],
        versionDesc: [
          { required: true, message: "请填写版本描述", trigger: "blur" }
        ],
        url: [{ required: true, message: "请填写下载地址", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getList();
  },
  filters: {
    clientStatus(status) {
      if (status === "ios") {
        return "ios";
      } else if (status === "android") {
        return "android";
      } else if (status === "other") {
        return "其他";
      }
    },
    formatCreateTime(time) {
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    },
    ListStatus(status) {
      if (status == 0) {
        return "否";
      } else if (status == 1) {
        return "是";
      }
    },
    dateTypeDetail(status) {
      if (status == 0) {
        return "小时";
      } else if (status == 1) {
        return "天";
      } else if (status == 2) {
        return "月";
      } else if (status == 3) {
        return "年";
      }
    }
  },
  methods: {
    submitForm() {
      console.log(66666)
      this.$refs["intergralForm"].validate(valid => {
        if (valid) {
          console.log(11111)
          if (this.isCreate) {
            this.editorIntergral();
          } else {
            this.$confirm("是否要修改该内容?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              this.editorIntergral();
            });
          }
        } else {
          console.log(22222)
          return false;
        }
      });
    },
    sendForm(){
      console.log(11111)
    },
    beforeUpload(file) {
      const _self = this;
      const fileName = file.uid;
      this.listObj[fileName] = {};
      console.log(11111);
      return new Promise((resolve, reject) => {
        console.log(22222);

        policy()
          .then(data => {
            // console.log('data.info.dir',data.info.dir);
            // console.log('data.info.dir',data.info.dir);
            _self.dataObj.policy = data.info.policy;
            _self.dataObj.signature = data.info.signature;
            _self.dataObj.ossaccessKeyId = data.info.accessKeyId;
            _self.dataObj.key = data.info.dir + `/${fileName}`;
            _self.dataObj.dir = data.info.dir;
            _self.dataObj.host = "https://static.5gyungou.com";
            // console.log('111111', 'https://static.5gyungou.com/'+ _self.dataObj.key)
            _self.listObj[fileName] = {
              hasSuccess: false,
              url: _self.dataObj.key,
              uid: file.uid,
              width: this.width,
              height: this.height
            };

            // {hasSuccess: false,url: 'https://static.5gyungou.com/'+ _self.dataObj.key, uid: file.uid, width: this.width, height: this.height};
            resolve(true);
          })
          .catch(err => {
            reject(false);
          });
      });
    },
    handleSuccess(response, file) {
      const uid = file.uid;
      const objKeyArr = Object.keys(this.listObj);
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          this.listObj[objKeyArr[i]].url =
            this.dataObj.host + "/" + this.dataObj.key;
          this.intergralForm.url = this.dataObj.host + "/" + this.dataObj.key;
          this.listObj[objKeyArr[i]].hasSuccess = true;
          return;
        }
      }
    },
    changeTimePicker(e) {
      this.$set(this.intergralForm, "activityTime", [e[0], e[1]]);
    },
    // 添加修改积分
    editorIntergral() {
      let msg = this.isCreate ? "添加" : "修改";
      // let intergralForm = {};
      // for (let i in this.intergralForm) {
      //   if (i != 'activityTime') {
      //     intergralForm[i] = this.intergralForm[i]
      //   }
      // }

      if (this.isCreate) {
        insertPackage(this.intergralForm).then(data => {
          this.selectDialogVisible = false;
          this.getList();
          // this.sortDialogData.dayNum = '';
          // this.sortDialogData.limitNum = '';
          this.$message({
            type: "success",
            message: msg + "成功"
          });
        });
      } else {
        updateAppPackageProduct(this.intergralForm).then(data => {
          this.selectDialogVisible = false;
          this.getList();
          // this.sortDialogData.dayNum = '';
          // this.sortDialogData.limitNum = '';
          this.$message({
            type: "success",
            message: msg + "成功"
          });
        });
      }
    },
     handleExceed(files, fileList) {
        this.$message({
          message: '您已经上传了一个文件，请删除之前操作再上传',
          type: 'warning',
          duration:1000
        });
      },
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
    },
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleDelete(index, row) {
      this.deleteAppPackage(row.id);
    },
    handleBatchOperate() {
      if (this.multipleSelection < 1) {
        this.$message({
          message: "请选择一条记录",
          type: "warning",
          duration: 1000
        });
        return;
      }
      let ids = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        ids.push(this.multipleSelection[i].id);
      }
      if (this.operateType == 1) {
        //删除
        this.deleteAppPackage(ids);
      } else {
        this.$message({
          message: "请选择批量操作类型",
          type: "warning",
          duration: 1000
        });
      }
    },
    createActivity() {
      this.selectDialogVisible = true;
      this.isCreate = true;
      this.intergralForm = {
        appType: "",
        mustUpdate: "",
        versionNum: "",
        versionDesc: "",
        url: ""
      };
      // this.getDialogList();
    },
    handleSelectSearch() {
      this.getDialogList();
    },
    handleDialogSizeChange(val) {
      this.dialogData.listQuery.pageNum = 1;
      this.dialogData.listQuery.pageSize = val;
      this.getDialogList();
    },
    handleDialogCurrentChange(val) {
      this.dialogData.listQuery.pageNum = val;
      this.getDialogList();
    },
    handleDialogSelectionChange(val) {
      this.dialogData.multipleSelection = val;
    },
    handleEditSort(index, row) {
      // console.log('row',row)
      this.selectDialogVisible = true;
      this.isCreate = false;
      // console.log(this.integralList)
      row.mustUpdate = row.mustUpdate.toString();
      // row.dateType = row.dateType.toString();
      this.intergralForm = row;
      // this.$set(this.intergralForm, "activityTime", [new Date(row.beginTime), new Date(row.endTime)]);
      // this.activityTime = [new Date(row.beginTime), new Date(row.endTime)];
      // this.intergralForm.id = row.id;
      // console.log('intergralForm',this.intergralForm)
      // this.type = 1;
      // this.sortDialogVisible=true;
      // this.sortDialogData.sort=row.sort;
      // this.sortDialogData.ids=[row.id];
    },
    getList() {
      this.listLoading = true;
      for (let i in this.listQuery) {
        if (this.listQuery[i] == "" || !this.listQuery[i]) {
          delete this.listQuery[i];
        }
      }
      let query = { ...this.listQuery };
      if (query.status == "2") {
        delete query.status;
      }

      fetchList(query).then(data => {
        this.listLoading = false;
        this.integralList = data.info;
        this.total = data.totalnum;
      });
    },
    deleteAppPackage(ids) {
      this.$confirm("是否要删除积分?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let data = {};
        if (Array.isArray(ids)) {
          data = { ids: ids };
        } else {
          data = { ids: [ids] };
        }
        // let data = { ids: ids }
        deleteAppPackage(data).then(data => {
          this.getList();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        });
      });
    },
    getDialogList() {
      return;
      fetchQuoteProduct(this.dialogData.listQuery).then(data => {
        // this.dialogData.list = data.info;
        this.dialogData.total = data.totalnum;
      });
    }
  }
};
</script>
<style>
.input-with-select .el-input-group__append {
  background-color: #fff;
}

.input-with-select .el-select .el-input {
  width: 130px;
}
</style>